package org.example.aicloud.controller;

import cn.hutool.core.lang.UUID;
import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.baidubce.qianfan.model.image.Text2ImageResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.example.aicloud.entity.Answer;
import org.example.aicloud.entity.enums.AiModelEnum;
import org.example.aicloud.entity.enums.AiTypeEnum;
import org.example.aicloud.service.IAnswerService;
import org.example.aicloud.util.AppVariable;
import org.example.aicloud.util.MinIoUtil;
import org.example.aicloud.util.ResultAjax;
import org.example.aicloud.util.SecurityUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RequestMapping("/qianfan")
@RestController
public class QianfanController {

    @Value("${qianfan.api-key}")
    private String apiKey;
    @Value("${qianfan.secret-key}")
    private String secretKey;

    @Resource
    private MinIoUtil minIoUtil;
    @Resource
    private IAnswerService answerService;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate redisTemplate;
    @RequestMapping("/chat")
    public ResultAjax chat(String question) {
        if (!StringUtils.hasLength(question)) {
            return ResultAjax.success("问题不能为空");
        }
        //执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.QIANFAN.getValue(),
                AiTypeEnum.CHAT.getValue());
        String result = ""; // 大模型返回的结构
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            // 获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResultAjax.error("请勿频繁调用接口！");
            }
            ChatResponse response = new Qianfan(apiKey, secretKey).chatCompletion()
                    .model("ERNIE-Speed-8K") // 使用 model 指定预置模型
                    .addMessage("user", question) // 添加用户消息 (此方法可以调用多次，以实现多轮对话的消息传递)
//                .temperature(0.7) // 自定义超参数
                    .execute(); // 发起请求
            result = response.getResult();
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(result);
            answer.setModel(AiModelEnum.QIANFAN.getValue());
            answer.setUid(SecurityUtil.getCurrentUser().getUid());
            answer.setType(AiTypeEnum.CHAT.getValue());
             isSave = answerService.save(answer);
        } catch (Exception e) {

        } finally {
            rLock.unlock();
        }
        if (isSave) {
            return ResultAjax.success(result);
        }
        return ResultAjax.error("操作失败，请重试");
    }

    @RequestMapping("/draw")
    public ResultAjax draw(String question) {
        if (!StringUtils.hasLength(question)) {
            return ResultAjax.success("问题不能为空");
        }
        //执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.QIANFAN.getValue(),
                AiTypeEnum.DRAW.getValue());
        String result = ""; // 大模型返回的结构
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            // 获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResultAjax.error("请勿频繁调用接口！");
            }
            Text2ImageResponse response = new Qianfan(apiKey, secretKey)
                    .text2Image()
                    .prompt(question)
                    .execute();
            byte[] image = response.getData().get(0).getImage();

            String fileName = "qf-" + UUID.randomUUID().toString().replace("-", "");
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(image)) {
                result = minIoUtil.upload(fileName, inputStream, "image/png");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(result);
            answer.setModel(AiModelEnum.QIANFAN.getValue());
            answer.setType(AiTypeEnum.DRAW.getValue());
            answer.setUid(SecurityUtil.getCurrentUser().getUid());
            isSave = answerService.save(answer);
        } catch (Exception e) {

        } finally {
            rLock.unlock();
        }
        if (isSave) {
                return ResultAjax.success(result);
        }
        return ResultAjax.error("操作失败，请重试！");
    }

    /**
     * 获取 Tongyi 聊天历史信息
     *
     * @return
     */
    @RequestMapping("/getchatlist")
    public ResultAjax getChatList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        int model = AiModelEnum.QIANFAN.getValue();
        int type = AiTypeEnum.CHAT.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid, model, type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        if (list == null) {
            QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);
            queryWrapper.eq("type", AiTypeEnum.CHAT.getValue());
            queryWrapper.eq("model", AiModelEnum.QIANFAN.getValue());
            queryWrapper.orderByDesc("aid");
            List<Answer> dataList = answerService.list(queryWrapper);
            redisTemplate.opsForValue().set(cacheKey, dataList, 1, TimeUnit.DAYS);
            return ResultAjax.success(dataList);
        } else {
            //System.out.println("触发了redis缓存！！！！！！！千帆");
            return ResultAjax.success(list);
        }


    }

    /**
     * 获取所有的绘画记录
     */
    @RequestMapping("/getdrawlist")
    public ResultAjax getDrawList() {
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("model", AiModelEnum.QIANFAN.getValue());
        queryWrapper.eq("type", AiTypeEnum.DRAW.getValue());
        queryWrapper.eq("uid", SecurityUtil.getCurrentUser().getUid());
        queryWrapper.orderByDesc("aid");
        return ResultAjax.success(answerService.list(queryWrapper));
    }
}
